﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using System.Text.Encodings.Web;

using System.Text.Json.Serialization;

using WXWorkSvc.Common.Models;

namespace WXWorkSvc.Private;

public static class WXWorkExtensions
{
    /// <summary>
    /// AddAuthentication
    /// AddControllers
    /// AddHttpClient
    /// AddHttpContextAccessor
    /// AddSqlServer_WXDbContext
    /// JsonTempDataSerializer
    /// WXWorkConfig
    /// WXWork
    /// </summary>
    /// <param name="services"></param>
    /// <param name="wxDbConnectionString"></param>
    /// <returns></returns>
    public static IServiceCollection AddWXWorkPrivate<T>(this IServiceCollection services, string wxDbConnectionString) where T : struct, Enum
    {
        services.AddSingleton<IRole, RoleBase<T>>();

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(option =>
        {
            option.LoginPath = new PathString("/account/login");
            option.AccessDeniedPath = new PathString("/account/denied");
        });

        services.AddControllers().AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
            options.JsonSerializerOptions.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
        });
        services.AddHttpClient().AddHttpContextAccessor();

        services.AddSqlServer<WXDbContext>(wxDbConnectionString);

        services.AddSingleton<WXWorkConfig>();
        services.AddSingleton<WXWork>();
        return services;
    }
    public static void UseWXWorkPrivate(this WebApplication app)
    {
        if (!app.Environment.IsDevelopment())
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.MapControllers();
        app.MapRazorPages();
    }
}
